package com.ccx.demo.open.common.controller;

import com.ccx.demo.business.common.dto.TabErrorLogInsertDTO;
import com.ccx.demo.business.common.service.ErrorLogService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.support.annotations.AppSwaggerGroup;
import com.support.annotations.VueSwaggerGroup;
import com.support.annotations.WechatSwaggerGroup;
import com.support.mvc.entity.IUser;
import com.support.mvc.entity.base.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Optional;

/**
 * 异常信息上报
 *
 * @author 谢长春 on 2022-02-22
 */
@Api(tags = "异常信息上报", hidden = true)
@RequestMapping("/open/error-log")
@Controller
@Slf4j
@RequiredArgsConstructor
public class OpenErrorLogController {
    private final ErrorLogService service;
    @AppSwaggerGroup
    @VueSwaggerGroup
    @WechatSwaggerGroup
    @PostMapping("/{traceId}")
    //@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_ADMIN_TEST', '{}_insert')")
    @ApiOperation(value = "异常信息上报", tags = {""})
    @ApiOperationSupport(author = "谢长春")
    @ResponseBody
    public Result<Void> insert(
            @ApiIgnore @AuthenticationPrincipal final IUser user,
            @PathVariable final String traceId,
            @RequestBody final String body
    ) {
        return new Result<Void>().call(() -> { // Controller 方法逻辑写在这里
            try {
                final TabErrorLogInsertDTO dto = new TabErrorLogInsertDTO();
                dto.setTraceId(traceId);
                dto.setMessage(body);
                service.insert(dto, Optional.ofNullable(user.fillUserByToken().getId()).orElse(0L));
            } catch (Exception e) {
                // 避免前端死循环，异常日志保存失败必须永远返回成功
                log.error(e.getMessage(), e);
            }
        });
    }

}
